package handler

import (
	"ear-hub/cache"
	"ear-hub/models"
	"ear-hub/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账户和密码不能为空",
		})
		return
	}

	redis_key := "ear_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "该用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return

	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
	return

}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var ear []models.Ear

	redis_key := "ear_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&ear)
		jsonData, _ := json.Marshal(ear)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &ear)
	}

	var total int64
	models.DB.Model(&models.Ear{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表展示成功",
		"data":  ear,
		"total": total,
	})
	return

}

func Comment(c *gin.Context) {
	userID, _ := strconv.Atoi(c.PostForm("uid"))
	earID, _ := strconv.Atoi(c.PostForm("eid"))
	content := c.PostForm("content")

	if userID == 0 || earID == 0 || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Comment{

		Content: content,
		UserID:  userID,
		EarID:   earID,
	}

	tx := models.DB.Begin()

	err := tx.Create(&data).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	var ear models.Ear
	err = tx.Where("id = ?", earID).First(&ear).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "该小说不存在",
		})
		return
	}

	ear.CommentCount++
	err = tx.Save(ear).Error

	tx.Commit()

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论数量增加成功",
	})
	return
}
